import { useEffect } from "react";
import { useReactive } from "ahooks";
import { notification } from "antd";

export default function globalModel() {
    let state = useReactive({
        isMaximized: true,
        currentWindow: remote.getCurrentWindow(),
        windowInnerHeight: window.innerHeight,
    });

    window.onresize = () => {
        state.windowInnerHeight = window.innerHeight;
    };

    useEffect(() => {
        const remoteSharedObject = remote.getGlobal("sharedObject");
        for (let key in remoteSharedObject) {
            state[key] = remoteSharedObject[key];
        }

        if (state.currentWindow) {
            state.currentWindow.on("maximize", () => {
                state.isMaximized = state.currentWindow.isMaximized();
            });

            state.currentWindow.on("unmaximize", () => {
                state.isMaximized = state.currentWindow.isMaximized();
            });
        }
    }, []);

    const remoteData = async (options) => {
        let { statusCode, message, result } = await requestRemoteData(options);
        if (statusCode === 0) {
            return result ? result : true;
        } else if (statusCode === 1) {
            let msgs = [message];
            if (Array.isArray(result)) msgs = msgs.concat(result);
            if (typeof result === "string") msgs.push(result);
            notification.error({ message: "登录过期了", description: msgs.join("；") });
            return null;
        } else if (statusCode >= 400) {
            let msgs = [message];
            if (Array.isArray(result)) msgs = msgs.concat(result);
            if (typeof result === "string") msgs.push(result);
            options.showError !== false && notification.error({ message: "错误信息", description: msgs.join("；") });
            logger.error(...msgs);
            return null;
        } else {
            return null;
        }
    };

    return { ...state, remoteData };
}
